//
//  LYScheduleView.m
//  SZBank
//
//  Created by LuoYao on 16/7/11.
//  Copyright © 2016年 LuoYao. All rights reserved.
//

#import "LYScheduleView.h"
#import "CKCalendarView.h"
#import "LYScheduleTableViewCell.h"

#import <EventKitUI/EventKitUI.h>

@interface LYScheduleView ()<EKEventEditViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    EKEventStore *_eventStore;/**< 事件市场 */
    NSArray<EKEvent *> *_scheduArray;/**< 日历事件清单 */
}
@property (nonatomic) CKCalendarView *calendarView;/**< 日历视图 */
@property (nonatomic) UITableView *listTableView;/**< 日历下方展示用的tableView */
@property (nonatomic) UITableView *detailListTableView;/**< 右侧详细tableView */
@property (nonatomic) UILabel *dateLabel;/**< 日期label */

@end
@implementation LYScheduleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        //初始事件市场
        _eventStore = [[EKEventStore alloc] init];
        
        
        
        //背景
        self.backImageView.image = [LocalDataManager getImageWithSourceOfPath:@"日程安排_背景"];
        
        //日历
        [self addSubview:self.calendarView];
        
        //tableView
        [self addSubview:self.listTableView];
        
        
        //回今天
        UIButton *nowDateBtn = [[UIButton alloc] initWithFrame:CGRectMake(_cKwidth * 0.25, _cKheight * 0.03, 100, 40)];
        [nowDateBtn setBackgroundImage:[LocalDataManager getImageWithSourceOfPath:@"日程安排_03"] forState:UIControlStateNormal];
        
        [nowDateBtn addTarget:self action:@selector(action_BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:nowDateBtn];
        
        
        //添加
        UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(_cKwidth * 0.85, _cKheight * 0.03, 100, 40)];
        [addBtn setBackgroundImage:[LocalDataManager getImageWithSourceOfPath:@"备忘录_增加"] forState:UIControlStateNormal];
        [addBtn addTarget:self action:@selector(action_addBtn) forControlEvents:UIControlEventTouchUpInside];
        
        [self addSubview: addBtn];
        
        
        //右侧详细tableView
        [self addSubview:self.detailListTableView];
        //左下日期
        [self addSubview:self.dateLabel];
        
        //选中的日历通知处理
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"date" object:nil];
        
    }
    return self;
}



#pragma mark 通知
- (void)notificationAction:(NSNotification *)notification{
    CKCalendarView *ck = [notification object];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *ckDate = [dateFormatter stringFromDate:ck.selectedDate];
    
    NSDate *startDate = [dateFormatter dateFromString:ckDate];
    
    NSDate *endDate = [NSDate dateWithTimeInterval:24 * 60 * 60 sinceDate:startDate];
    
    NSPredicate *predicate = [_eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:nil];
    
     _scheduArray = [_eventStore eventsMatchingPredicate:predicate];
    
    self.dateLabel.text = [[NSString stringWithFormat:@"%@",ckDate] substringToIndex:11];
    
    [self.listTableView reloadData];
    [self.detailListTableView reloadData];
}



- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"date" object:nil];
}

#pragma mark - 点击事件
//回今天
- (void)action_BtnClick:(UIButton *)sender{
    
}

//add
- (void)action_addBtn{
    
    
    EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];
    addController.editViewDelegate = self;
    addController.eventStore = _eventStore;

    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:addController animated:YES completion:nil];

}


#pragma mark - ekevViewEditDelegate
- (void)eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action{
    switch (action) {
        case EKEventEditViewActionCanceled:
            break;
            
        case EKEventEditViewActionSaved:
        {
            //创建事件
            EKEvent *event  = [EKEvent eventWithEventStore:_eventStore];
            event.title     = controller.event.title;
            event.location = controller.event.location;
            
            
            event.startDate = controller.event.startDate;
            event.endDate   = controller.event.endDate;;
            event.allDay = controller.event.allDay;
            
            
            //添加提醒
//            [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
//            [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];
            
            
            //保存
            [event setCalendar:[_eventStore defaultCalendarForNewEvents]];
            NSError *err;
            [_eventStore saveEvent:event span:EKSpanThisEvent error:&err];
            
        
        }
            
        default:
            break;
    }
    
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (EKCalendar *)eventEditViewControllerDefaultCalendarForNewEvents:(EKEventEditViewController *)controller{
    
    //localSourece
    EKSource* localSource;
    for (EKSource* source in _eventStore.sources) {
        if (source.sourceType == EKSourceTypeLocal)
        {
            localSource = source;
            break;
        }
    }

    //calendar
    EKCalendar *newCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:_eventStore];
    newCalendar.source = localSource;
    newCalendar.title = @"新建事件";

    
    return newCalendar;
}


#pragma mark - uitableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.listTableView]) {
        return _scheduArray.count;
    }else{
        return _scheduArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:self.listTableView]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listcell" forIndexPath:indexPath];
        cell.textLabel.text = _scheduArray[indexPath.row].title;
        cell.textLabel.font = [UIFont systemFontOfSize:FONT_SIZE];
        return cell;
        
    }else{
        LYScheduleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
        cell.dic = @{@"title":_scheduArray[indexPath.row].title,@"startDate":_scheduArray[indexPath.row].startDate,@"endDate":_scheduArray[indexPath.row].endDate};
        return cell;
    }
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.listTableView]) {
        return 55;
    }
    else{
        return 100;
    }
}


#pragma mark - getter
- (CKCalendarView *)calendarView{
    _calendarView = ({
        CKCalendarView  *calendar = [[CKCalendarView alloc] initWithStartDay:startMonday frame:CGRectMake(_cKwidth * 0.005, 0, _cKwidth * 0.37, _cKheight * 0.2)];
        calendar.userInteractionEnabled = YES;
        [calendar setTitleColor:[UIColor redColor]];
        [calendar setButtonColor:[UIColor lightTextColor]];
        calendar.backgroundColor = [UIColor clearColor];
        [calendar setDayOfWeekBottomColor:[UIColor blackColor] topColor:[UIColor blackColor]];
        [calendar setInnerBorderColor:[UIColor clearColor]];
        
        calendar;
    });
    return _calendarView;
}


- (UITableView *)listTableView{
    if (!_listTableView) {
        _listTableView = ({
        
            UITableView *tv = [[UITableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.005, _cKheight * 0.65, _cKwidth * 0.37, _cKheight * 0.35) style:UITableViewStylePlain];
            tv.delegate = self;
            tv.dataSource = self;
            
            
            [tv registerClass:[UITableViewCell class] forCellReuseIdentifier:@"listcell"];
            
            tv;
        
        });
    }
    
    return _listTableView;
}


- (UITableView *)detailListTableView{
    if (!_detailListTableView) {
        _detailListTableView = [[UITableView alloc] initWithFrame:CGRectMake(_cKwidth * 0.4, _cKheight * 0.1, _cKwidth * 0.55, _cKheight * 0.8)];
        _detailListTableView.dataSource = self;
        _detailListTableView.delegate = self;
        
        _detailListTableView.tableFooterView = [[UIView alloc] init];
        _detailListTableView.backgroundColor = [UIColor colorWithRed:0.9452 green:0.9452 blue:0.9452 alpha:1.0];
        
        [_detailListTableView registerClass:[LYScheduleTableViewCell class] forCellReuseIdentifier:@"detailCell"];
    }
    return _detailListTableView;
}


- (UILabel *)dateLabel{
    if (!_dateLabel) {
        _dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.005, _cKheight * 0.6, _cKwidth * 0.2, _cKheight * 0.05)];
        _dateLabel.font = [UIFont systemFontOfSize:FONT_SIZE];
    }
    return _dateLabel;
}
@end
